package com.cdu.interceptor;

import com.auth0.jwt.JWT;
import com.cdu.util.JWTUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Base64Utils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;

/**
 * @program: easy-help-v2
 * @description:
 * @author: hanabi
 * @create: 2022-05-19 10:46
 **/
@Slf4j
public class JwtInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws UnsupportedEncodingException {
        if (request.getMethod().equals("OPTIONS")){
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }
        String token = new String(Base64Utils.decodeFromUrlSafeString(request.getHeader("Authentication")), "UTF-8");
        if (token != null) {
            boolean result = JWTUtil.verifyToken(token);
            if (result) {
                log.info("通过拦截器");
                String userId = JWT.decode(token).getClaim("userId").asString();
                request.setAttribute("userId", userId);
                return true;
            }
        }
        log.info("认证失败");

        return false;
    }
}
